package org.blogsomy.jaas;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.blogsomy.model.dao.DaoFacade;
import org.blogsomy.model.dao.UserDao;
import org.blogsomy.model.entities.User;
import org.springframework.context.ApplicationContext;

import com.google.code.lightsomy.web.ApplicationContextRegistry;

public class AuthListener implements ServletRequestListener {

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
		HttpSession session = request.getSession();
		
		if (session.getAttribute("user") == null && request.getRemoteUser() != null) {
			ApplicationContext ac = ApplicationContextRegistry.getApplicationContext();
			DaoFacade facade = (DaoFacade) ac.getBean("daoFacade");
			UserDao userDao = facade.getUserDao();
			User u = userDao.find(request.getRemoteUser());
			
			if (u != null) {
				session.setAttribute("user", u);
			}
		}
	}
	
	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
	}

}
